import React, { useEffect, useState, useRef } from 'react';
import {
  Button,
  View,
  Image,
  Text,
  ScrollView
} from '@tarojs/components';
import Taro, { useShareAppMessage } from '@tarojs/taro';
import {
  queryUserInfo,
  queryUserPoints,
  queryUserHistory,
  queryPointsRedeem,
  postUserInvitations
} from '@/api';
import {
  AtModal
} from 'taro-ui';
import NavBar from '@/components/NavBar';
import './index.scss';

const Task = () => {
  const [isOpened, setIsOpened] = useState(false);
  const [titleBarHeight, setTitleBarHeight] = useState(0);
  const [tab, setTab] = useState(0);
  const [point, setPoint] = useState(0);
  const [userInfo, setUserInfo] = useState({});
  const [list, setList] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const pageNo = useRef(1);

  useEffect(() => {
    Taro.getSystemInfo({
      success: (res) => {
        let height = res.titleBarHeight + res.statusBarHeight
        setTitleBarHeight(height)
      }
    });
    onLoadData();
    onLoadPoint();
    onLoadHistory();
  }, []);

  useShareAppMessage((res)=>{
    if (res.from == 'button') {
      onPostInvitations();
      return {
        title: '快来围观我的写真吧',
        path: '/pages/index/index',
        imageUrl: 'https://jala-test-images.sndaurl.cn/images/share_img.png'
      }
    }
  });

  const onPostInvitations = async()=>{
    await postUserInvitations();
    onLoadData();
  }

  const onLoadPoint = () => {
    queryUserPoints({})
      .then(res=>{
        setPoint(res.currentPoint);
      })
  }

  const onLoadData = () => {
    queryUserInfo({})
      .then(res=>{
        setUserInfo(res);
      })
  }

  const onLoadHistory = () => {
    let params = {
      page: pageNo.current,
      page_size: 20
    }
    queryUserHistory(params)
      .then(res=>{
        let data = res.list || [];
        let arr = [];
        if (pageNo.current === 1) {
          arr = data;
        } else {
          arr = [...list, ...data];
        }
        if (res.list.length < 20) {
          setHasMore(false)
        }
        setList(arr);
      })
  }

  const onLoadMore = () => {
    if (hasMore) {
      pageNo.current = pageNo.current + 1;
      onLoadHistory();
    }
  }

  const doBack = () => {

  }

  const onShowHistory = () => {
    setIsOpened(true);
  }

  const onRedeem = () => {
    queryPointsRedeem()
      .then(res=>{
        if (res.Code == 454) {
          Taro.showToast({
            title: '积分不足',
            icon: 'none'
          })
        } else {
          onLoadData();
        }
      })
  }

  const onJoin = () => {
    let {
      dy_type
    } = userInfo;
    let shopId = '';
    let couponId = '';
    // dy_v1 对应自然堂官方旗舰店
    // dy_v2 对应自然堂美妆旗舰店
    // dy_v3 对应抖音自然堂男士旗舰店
    // dy_v4 对应自然堂个护旗舰店
    if (dy_type == 'dy_v1') {
      shopId = '12550325';
      couponId = '7306826482163663116';
    }
    if (dy_type == 'dy_v2') {
      shopId = '41964338';
      couponId = '7306826931721601316';
    }
    if (dy_type == 'dy_v2') {
      shopId = '18308067';
      couponId = '7306827867424473380';
    }
    if (dy_type == 'dy_v3') {
      shopId = '91632294';
      couponId = '7306828487422820645';
    }
    tt.openEcShop({
      shopId: shopId,
      tabType: 1,
      success: (res) => {
        console.log('openEcShop', res)
        setShowMember(false)
      },
      fail: (res) => {
        console.log("调用失败", res);
      }
    })
  }

  return (
    <View className='task_container'>
      {/* <NavBar
        title="任务中心"
        onClick={()=>{doBack()}}
      /> */}
      <View
        className='task_section'
        style={{
          paddingTop: `${titleBarHeight}px`
        }}
      >
        <View className='task_main'>
          <View className='task_main_info'>
            <View className='task_main_info_title'>剩余变妆次数</View>
            <View className='task_main_info_value'>
              <Text className='task_main_info_value_num'>{userInfo?.num || 0}</Text>
              次
            </View>
          </View>
          <View className='task_main_history' onClick={()=>{onShowHistory()}}>
            历史明细
            <Image
              src='https://jala-test-images.sndaurl.cn/images/right.png'
              className='task_main_history_icon'
            />
          </View>
          <View className='task_main_content'>
            <View className='task_main_content_title'>
              <Image
                className='task_main_content_title_icon'
                src='https://jala-test-images.sndaurl.cn/images/task_title.png'
                mode='widthFix'
              />
            </View>
            <View className='task_main_content_section'>
              <Image
                src='https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>加入会员（1/1）</View>
              <View className='task_main_content_section_desc w_406'>变妆次数+3，活动期间限一次</View>
              <View className={`task_main_content_section_action pedding`}>
                已完成
              </View>
            </View>
            <View className='task_main_content_section'>
              <Image
                src='https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>邀请好友（{userInfo.invitations}/5）</View>
              <View className='task_main_content_section_desc w_406'>成功邀请1位用户，即可获得1次变妆机会</View>
              {
                userInfo.invitations == 5 ? (
                  <View className='task_main_content_section_action pedding'>已完成</View>
                ) : (
                  <Button
                    openType='share'
                    className={`task_main_content_section_action`}
                  >
                    完成任务
                  </Button>
                )
              }

            </View>
            <View className='task_main_content_section'>
              <Image
                src='https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>订阅店铺（0/1）</View>
              <View className='task_main_content_section_desc w_406'>首次订阅关注店铺，变妆次数+1，活动期间限1次</View>
              <View className={`task_main_content_section_action`} onClick={()=>{onJoin()}}>
                完成任务
              </View>
            </View>
            <View className='task_main_content_section'>
              <Image
                src='https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>积分兑换（当前积分：{point}）</View>
              <View className='task_main_content_section_desc w_406'>自然堂100会员积分可兑换1次变妆机会，不限次数</View>
              <View className={`task_main_content_section_action`} onClick={()=>{onRedeem()}}>
                完成任务
              </View>
            </View>
            <View className='task_main_content_section'>
              <Image
                src='https://jala-test-images.sndaurl.cn/images/arrowBg.png'
                className='task_main_content_section_icon'
              />
              <View className='task_main_content_section_title'>获取更多积分</View>
              <View className='task_main_content_section_desc w_574'>可抖音搜索“自然堂官方商城”小程序进行购买商品，即可获取会员积分</View>
            </View>
          </View>
        </View>
      </View>
      <AtModal
        isOpened={isOpened}
        closeOnClickOverlay={false}
      >
        <View className='history_view'>
          <View className='history_view_title'>
            历史明细
            <Image
              src='https://jala-test-images.sndaurl.cn/images/closeIcon.png'
              className='history_view_title_icon'
              onClick={()=>{setIsOpened(false)}}
            />
          </View>
          <ScrollView
            scrollY={true}
            style={{
              height: '640rpx'
            }}
            className='history_view_content'
            onScrollToLower={()=>{onLoadMore()}}
          >
            {
              list && list.map((item, index) =>
                <View className='history_view_content_section' key={index}>
                  <View className='history_view_content_section_title'>{item.desc}</View>
                  <View className='history_view_content_section_time'>生成时间：{item.create_time}</View>
                  <View className='history_view_content_section_value'>{item.num}</View>
                </View>
              )
            }
          </ScrollView>
        </View>
      </AtModal>
    </View>
  )
}
export default Task;
